package com.example.project.common.ex;

import com.example.project.common.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        Integer code = e.getCode() == null ? 400 : e.getCode();
        return Result.fail(code, e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<Void> handleMethodArgumentNotValid(MethodArgumentNotValidException e) {
        List<String> messages = e.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        String msg = String.join("；", messages);
        return Result.fail(400, msg);
    }

    @ExceptionHandler({BindException.class})
    public Result<Void> handleBindException(BindException e) {
        List<String> messages = e.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        String msg = String.join("；", messages);
        return Result.fail(400, msg);
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public Result<Void> handleConstraintViolation(ConstraintViolationException e) {
        String msg = e.getConstraintViolations().stream()
                .map(v -> v.getMessage())
                .collect(Collectors.joining("；"));
        return Result.fail(400, msg);
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        return Result.fail(500, e.getMessage());
    }
}


